﻿using System;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Input;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Xml.Linq;
using QXGameEngine.Control;
using QXGameEngine.Interface;
using System.Windows.Shapes;

namespace QXGameEngine.Logic {
    public static class Super {

        //游戏音乐音效
        public static MediaElement gameMusic, gameAudio;

        /// <summary>
        /// 通过正切值获取精灵的朝向代号
        /// </summary>
        /// <param name="targetX">目标点的X值</param>
        /// <param name="targetY">目标点的Y值</param>
        /// <param name="currentX">当前点的X值</param>
        /// <param name="currentY">当前点的Y值</param>
        /// <returns>精灵朝向代号(以北为0顺时针依次1,2,3,4,5,6,7)</returns>
        public static double GetDirectionByTan(double targetX, double targetY, double currentX, double currentY) {
            double tan = (targetY - currentY) / (targetX - currentX);
            if (Math.Abs(tan) >= Math.Tan(Math.PI * 3 / 8) && targetY <= currentY) {
                return 0;
            } else if (Math.Abs(tan) > Math.Tan(Math.PI / 8) && Math.Abs(tan) < Math.Tan(Math.PI * 3 / 8) && targetX > currentX && targetY < currentY) {
                return 1;
            } else if (Math.Abs(tan) <= Math.Tan(Math.PI / 8) && targetX >= currentX) {
                return 2;
            } else if (Math.Abs(tan) > Math.Tan(Math.PI / 8) && Math.Abs(tan) < Math.Tan(Math.PI * 3 / 8) && targetX > currentX && targetY > currentY) {
                return 3;
            } else if (Math.Abs(tan) >= Math.Tan(Math.PI * 3 / 8) && targetY >= currentY) {
                return 4;
            } else if (Math.Abs(tan) > Math.Tan(Math.PI / 8) && Math.Abs(tan) < Math.Tan(Math.PI * 3 / 8) && targetX < currentX && targetY > currentY) {
                return 5;
            } else if (Math.Abs(tan) <= Math.Tan(Math.PI / 8) && targetX <= currentX) {
                return 6;
            } else if (Math.Abs(tan) > Math.Tan(Math.PI / 8) && Math.Abs(tan) < Math.Tan(Math.PI * 3 / 8) && targetX < currentX && targetY < currentY) {
                return 7;
            } else {
                return 0;
            }
        }

        /// <summary>
        /// 寻路模式中根据单元格方向来判断精灵朝向
        /// </summary>
        /// <param name="targetX">目标点的X值</param>
        /// <param name="targetY">目标点的Y值</param>
        /// <param name="currentX">当前点的X值</param>
        /// <param name="currentY">当前点的Y值</param>
        /// <returns>精灵朝向代号(以北为0顺时针依次1,2,3,4,5,6,7)</returns>
        public static double GetDirectionByAspect(int targetX, int targetY, int currentX, int currentY) {
            int direction = 2;
            if (targetX < currentX) {
                if (targetY < currentY) {
                    direction = 7;
                } else if (targetY == currentY) {
                    direction = 6;
                } else if (targetY > currentY) {
                    direction = 5;
                }
            } else if (targetX == currentX) {
                if (targetY < currentY) {
                    direction = 0;
                } else if (targetY > currentY) {
                    direction = 4;
                }
            } else if (targetX > currentX) {
                if (targetY < currentY) {
                    direction = 1;
                } else if (targetY == currentY) {
                    direction = 2;
                } else if (targetY > currentY) {
                    direction = 3;
                }
            }
            return direction;
        }

        /// <summary>
        /// 根据点商值计算角度
        /// </summary>
        /// <param name="y">y2-y1值</param>
        /// <param name="x">x2-x1值</param>
        /// <returns>直角坐标系角度</returns>
        public static double GetAngle(double y, double x) {
            return Math.Atan2(y, x) / Math.PI * 180;
        }

        /// <summary>
        /// 判断点是否在圆内
        /// </summary>
        /// <param name="target">目标点坐标</param>
        /// <param name="center">圆心坐标</param>
        /// <param name="radius">圆半径</param>
        /// <returns></returns>
        public static bool InCircle(Point target, Point center, double radius) {
            return Math.Pow(target.X - center.X, 2) + Math.Pow(target.Y - center.Y, 2) <= Math.Pow(radius, 2) ? true : false;
        }

        /// <summary>
        /// 判断点是否在多边形内(射线法)
        /// </summary>
        /// <param name="target">目标点</param>
        /// <param name="range">多边形各顶点</param>
        /// <returns></returns>
        public static bool InPolygon(Point target, Point[] range) {
            int n = 0, count = 0;
            for (int i = 0; i < range.Length; i++) {
                n = (i == range.Length - 1) ? 0 : n + 1;
                if ((range[i].Y != range[n].Y) && (((target.Y >= range[i].Y) && (target.Y < range[n].Y)) || ((target.Y >= range[n].Y) && (target.Y < range[i].Y))) && (target.X < (range[n].X - range[i].X) * (target.Y - range[i].Y) / (range[n].Y - range[i].Y) + range[i].X)) {
                    count++;
                }
            }
            return (count % 2 > 0) ? true : false;
        }

        /// <summary>
        /// 根据两点及延伸长度获取延伸后的点
        /// </summary>
        /// <param name="start">起点</param>
        /// <param name="end">旧终点</param>
        /// <param name="Lenght">延伸后的最终长度</param>
        /// <returns>延伸后的终点</returns>
        public static Point GetExtensionPoint(Point start, Point end, int Lenght) {
            double scale = Math.Sqrt(Math.Pow(end.Y - start.Y, 2) + Math.Pow(end.X - start.X, 2)) / Lenght;
            return new Point(start.X + (end.X - start.X) / scale, start.Y + (end.Y - start.Y) / scale);
        }

        /// <summary>
        /// 根据45度四象限获取矩形四个顶点(直线穿梭魔法用)
        /// </summary>
        /// <param name="angle">旋转角度</param>
        /// <param name="start">矩形中线起点</param>
        /// <param name="end">矩形中线终点</param>
        /// <param name="radius">矩形中线与边距离</param>
        /// <returns>四个顶点</returns>
        public static Point[] GetRectRange(double angle, Point start, Point end, int radius) {
            if ((angle >= 45 && angle <= 135) || (angle >= -135 && angle <= -45)) {
                return new Point[]{
                    new Point(start.X - radius, start.Y),
                    new Point(start.X + radius, start.Y),
                    new Point(end.X + radius, end.Y),
                    new Point(end.X - radius, end.Y),
                };
            } else {
                return new Point[]{
                    new Point(start.X, start.Y - radius),
                    new Point(start.X, start.Y + radius),
                    new Point(end.X, end.Y + radius),
                    new Point(end.X, end.Y - radius),
                };
            }
        }

        /// <summary>
        /// 创建彩虹笔刷
        /// </summary>
        /// <param name="brush">笔刷</param>
        /// <param name="r0">渐变起步红</param>
        /// <param name="g0">渐变起步绿</param>
        /// <param name="b0">渐变起步蓝</param>
        /// <param name="r1">渐变转折红</param>
        /// <param name="g1">渐变转折绿</param>
        /// <param name="b1">渐变转折蓝</param>
        /// <param name="r2">渐变结束红</param>
        /// <param name="g2">渐变结束绿</param>
        /// <param name="b2">渐变结束蓝</param>
        public static LinearGradientBrush CreateRainbowBrush(byte r0, byte g0, byte b0, byte r1, byte g1, byte b1) {
            return new LinearGradientBrush() {
                StartPoint = new Point(0, 0),
                EndPoint = new Point(0, 1),
                GradientStops = new GradientStopCollection() {
                    new GradientStop() {
                        Color = Color.FromArgb(255, r0, g0, b0),
                        Offset = 0
                    },
                    new GradientStop() {
                        Color = Color.FromArgb(255, r1, g1, b1),
                        Offset = 1
                    }
                }
            };
        }

        /// <summary>
        /// 合成角色装备
        /// </summary>
        /// <param name="bodyAddress">身体图片地址</param>
        /// <param name="weaponAddress">武器图片地址</param>
        /// <param name="width">合成图宽</param>
        /// <param name="height">合成图高</param>
        /// <param name="offset">身体偏移量</param>
        /// <returns>角色装备合成图</returns>
        public static WriteableBitmap ComposeEquip(string bodyAddress, string weaponAddress, int width, int height, Point offset) {
            WriteableBitmap writeableBitmap = new WriteableBitmap(width, height);
            TranslateTransform translateTransform = new TranslateTransform() {
                X = offset.X,
                Y = offset.Y
            };
            Image image = new Image() {
                Source = Super.GetImage(bodyAddress)
            };
            writeableBitmap.Render(image, translateTransform);
            image.Source = Super.GetImage(weaponAddress);
            writeableBitmap.Render(image, null);
            writeableBitmap.Invalidate();
            return writeableBitmap;
        }

        /// <summary>
        /// 判断精灵是否与对象敌对
        /// </summary>
        /// <param name="obj">自身精灵</param>
        /// <param name="obj">对象精灵</param>
        /// <returns>是/否</returns>
        public static bool IsOpposition(QXSprite me, QXSprite obj) {
            //假如对象为自己则返回否
            if (me == obj || obj.VLife == 0) {
                return false;
                //假如对象是邪恶状态或PK值大于等于7则返回是
            } else if (obj.PKMode == PKModes.Whole || obj.VPK >= 7) {
                return true;
            } else {
                //根据自身的PK模式与对方的PK模式进行比较进行相应返回
                switch (me.PKMode) {
                    case PKModes.Peace:
                        return false;
                    case PKModes.Whole:
                        return true;
                    case PKModes.GoodAndEvil:
                    //暂时只有怪物方面逻辑
                    //return (obj.Name != "Leader" && obj.LockObject != null) ? true : false;
                    case PKModes.Faction:
                        return me.VFaction != obj.VFaction ? true : false;
                    case PKModes.Clan:
                        return me.VClan != obj.VClan ? true : false;
                    default:
                        return false;
                }
            }
        }

        /// <summary>
        /// 从项目相对路径加载图片并缓存
        /// </summary>
        /// <param name="address">图片地址</param>
        /// <returns>图片源</returns>
        public static BitmapSource GetImage(string address) {
            return new BitmapImage(new Uri(string.Format(@"{0}", address), UriKind.Relative));
        }

        public static Dictionary<string, XElement> Settings = new Dictionary<string, XElement>();
        /// <summary>
        /// 加载XElement类型系统参数及设置并缓存
        /// </summary>
        /// <param name="key">字典中的键名</param>
        /// <param name="element">XElement</param>
        public static void LoadXElement(string key, XElement element) {
            if (!Settings.ContainsKey(key)) {
                Settings.Add(key, element);
            }
        }
        /// <summary>
        /// 获取XML文件树节点段XElement
        /// </summary>
        /// <param name="XML">XML文件载体</param>
        /// <param name="newroot">要查找的独立节点</param>
        /// <returns>独立节点XElement</returns>
        public static XElement GetXElement(XElement XML, string newroot) {
            return XML.DescendantsAndSelf(newroot).Single();
        }
        /// <summary>
        /// 获取XML文件树节点段XElement
        /// </summary>
        /// <param name="xml">XML文件载体</param>
        /// <param name="mainnode">要查找的主节点</param>
        /// <param name="attribute">主节点条件属性名</param>
        /// <param name="value">主节点条件属性值</param>
        /// <returns>以该主节点为根的XElement</returns>
        public static XElement GetXElement(XElement XML, string newroot, string attribute, string value) {
            return XML.DescendantsAndSelf(newroot).Single(X => X.Attribute(attribute).Value == value);
        }

        public static Dictionary<string, Storyboard> storyboard = new Dictionary<string, Storyboard>();
        /// <summary>
        /// 创建新的精灵Storyboard移动动画板
        /// </summary>
        /// <param name="key">精灵名</param>
        public static void NewStoryboard(string key) {
            RemoveStoryboard(key);
            storyboard.Add(key, new Storyboard());
        }

        /// <summary>
        /// 暂停精灵Storyboard移动动画板
        /// </summary>
        /// <param name="sprite">对象精灵</param>
        public static void RemoveStoryboard(string key) {
            if (storyboard.ContainsKey(key)) {
                storyboard[key].Pause();
                storyboard[key] = null;
                storyboard.Remove(key);
            }
        }

        /// <summary>
        /// 在精灵头顶显示文字
        /// </summary>
        /// <param name="sprite">对象精灵</param>
        /// <param name="italic">字体是否倾斜</param>
        /// <param name="name">文字控件名</param>
        /// <param name="content">文字内容</param>
        /// <param name="fontsize">字体大小</param>
        /// <param name="fontcolor">文字颜色</param>
        /// <param name="borderwidth">边框宽</param>
        public static void ShowText(QXSprite sprite, FontWeight weight, FontStyle style, string content, int size, Color fontcolor) {
            //添加进父画布中
            sprite.ParentCanvas.Children.Add(new QXText() {
                Weight = weight,
                Fontstyle = style,
                Text = content,
                Color = new SolidColorBrush(fontcolor),
                Size = size,
                X = sprite.Coordinate.X - sprite.CenterX,
                Y = sprite.Coordinate.Y - sprite.CenterY - Math.Abs(sprite.DescribtionTop), //垂直居顶处理
                TotalWidth = sprite.SingleWidth
            });
        }

        /// <summary>
        /// 精灵物理攻击并产生伤害
        /// </summary>
        /// <param name="attacker">发起攻击精灵</param>
        public static void DoInjure(QXSprite attacker) {
            if (attacker.LockObject == null) { return; }
            //捕获敌人精灵
            QXSprite enemy = attacker.ParentCanvas.FindName(attacker.LockObject) as QXSprite;
            //首先进行闪避判断
            if (random.Next(100) >= (attacker.VHit - enemy.VDodge)) {
                ShowText(enemy, FontWeights.Bold, FontStyles.Italic, "Miss", 28, Color.FromArgb(255, 171, 199, 255));
            } else {
                int injure = 0;
                double atk;
                if (attacker.Action == Actions.Attack) {
                    atk = attacker.VAttackMin + random.Next((int)(attacker.VAttackMax - attacker.VAttackMin));
                    injure = atk > enemy.VDefense ? Convert.ToInt32(atk - enemy.VDefense) : 0;
                } else if (attacker.Action == Actions.Magic) {
                    atk = attacker.VMagicMin + random.Next((int)(attacker.VMagicMax - attacker.VMagicMin));
                    injure = atk > enemy.VMagicDefense ? Convert.ToInt32(atk - enemy.VMagicDefense) : 0;
                }
                //判断是否暴击
                if (random.Next(100) <= (attacker.VBurst - enemy.VBlock)) {
                    injure *= 2;
                    ShowText(enemy, FontWeights.Bold, FontStyles.Italic, string.Format("{0}!!", injure.ToString()), 28, Color.FromArgb(255, 235, 179, 71));
                } else {
                    ShowText(enemy, FontWeights.Bold, FontStyles.Normal, injure.ToString(), 26, enemy.Name == "Leader" ? Colors.Red : Colors.Yellow);
                }
                BattleHandle(attacker, enemy, injure);
            }
        }

        public static Random random = new Random();
        /// <summary>
        /// 精灵魔法攻击并产生伤害
        /// </summary>
        /// <param name="magic">魔法对象</param>
        public static void DoInjure(QXMagic magic) {
            QXSprite magicer = magic.ParentCanvas.FindName(magic.MagicOwner) as QXSprite;
            QXSprite enemy;
            for (int i = 0; i < magic.ParentCanvas.Children.Count; i++) {
                if (magic.ParentCanvas.Children[i] is QXSprite) {
                    enemy = magic.ParentCanvas.Children[i] as QXSprite;
                    if (enemy.Visibility == Visibility.Visible) {
                        switch (magic.Mode) {
                            case 0:
                                if (InCircle(enemy.Coordinate, magic.Coordinate, magic.Radius) && IsOpposition(magicer, enemy)) {
                                    ProduceInjury(magicer, enemy, magic);
                                }
                                break;
                            case 1:
                                if (InPolygon(enemy.Coordinate,
                                    GetRectRange(magic.Angle,
                                                 magicer.Coordinate,
                                                 GetExtensionPoint(magicer.Coordinate, magicer.MagicTarget, (int)magic.BodyWidth),
                                                 magic.Radius)
                                    )
                                    && IsOpposition(magicer, enemy)) {
                                    ProduceInjury(magicer, enemy, magic);
                                }
                                break;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 持续魔法效果产生伤害
        /// </summary>
        /// <param name="attacker">攻击者</param>
        /// <param name="enemy">敌人</param>
        /// <param name="injure">伤害值</param>
        public static void DoInjure(QXSprite attacker, QXSprite enemy, double injure) {
            ShowText(enemy, FontWeights.Bold, FontStyles.Normal, injure.ToString(), 26, enemy.Name == "Leader" ? Colors.Red : Colors.Yellow);
            BattleHandle(attacker, enemy, injure);
        }

        public static Color[] AdditionalEffectColor;
        /// <summary>
        /// 产生魔法类伤害
        /// </summary>
        /// <param name="magicer">施法者</param>
        /// <param name="enemy">敌人</param>
        /// <param name="magic">魔法</param>
        private static void ProduceInjury(QXSprite magicer, QXSprite enemy, QXMagic magic) {
            double injure = magic.ATK + magicer.VMagicMin + random.Next((int)(magicer.VMagicMax - magicer.VMagicMin)) - enemy.VMagicDefense;
            enemy.AdditionalEffect[magic.AdditionalEffectCode] = magic.AdditionalEffect;
            enemy.AdditionalEffectTime[magic.AdditionalEffectCode] = magic.AdditionalEffectTime;
            ShowText(enemy, FontWeights.Bold, FontStyles.Normal, injure.ToString(), 26, enemy.Name == "Leader" ? Colors.Red : Colors.Yellow);            //产生附加属性效果
            switch (magic.AdditionalEffectCode) {
                case 0:
                    //麻痹
                    enemy.Buff[5] = enemy.AdditionalEffect[magic.AdditionalEffectCode];
                    enemy.Buff[6] = enemy.AdditionalEffect[magic.AdditionalEffectCode];
                    enemy.Buff[7] = enemy.AdditionalEffect[magic.AdditionalEffectCode];
                    enemy.Action = Actions.Stop;
                    break;
                case 1:
                    //混乱
                    break;
                case 2:
                    //冰冻
                    RemoveStoryboard(enemy.Name);
                    break;
                case 3:
                    //中毒
                    enemy.AdditionalEffectSprite = magicer.Name;
                    break;
                case 4:
                    //燃烧
                    enemy.Buff[9] = -enemy.AdditionalEffect[magic.AdditionalEffectCode];
                    enemy.Buff[10] = -enemy.AdditionalEffect[magic.AdditionalEffectCode];
                    enemy.Buff[12] = -enemy.AdditionalEffect[magic.AdditionalEffectCode];
                    break;
                case 5:
                    //虚弱
                    enemy.Buff[1] = -enemy.AdditionalEffect[magic.AdditionalEffectCode];
                    enemy.Buff[2] = -enemy.AdditionalEffect[magic.AdditionalEffectCode];
                    enemy.Buff[13] = -enemy.AdditionalEffect[magic.AdditionalEffectCode];
                    enemy.Buff[14] = -enemy.AdditionalEffect[magic.AdditionalEffectCode];
                    enemy.Buff[15] = -enemy.AdditionalEffect[magic.AdditionalEffectCode];
                    break;
            }
            enemy.MaskColor = new SolidColorBrush(AdditionalEffectColor[magic.AdditionalEffectCode]);
            //为精灵附加有可能的特效装饰
            if (magic.DecorationCode != -1 && enemy.RootCanvas.FindName(string.Format("Decoration{0}", magic.AdditionalEffectCode)) == null) {
                QXDecoration decoration = new QXDecoration() {
                    Name = string.Format("Decoration{0}", magic.AdditionalEffectCode),
                    Code = magic.DecorationCode,
                    BodyWidth = magic.DecorationWidth,
                    BodyHeight = magic.DecorationHeight,
                    EndFrame = magic.DecorationEndFrame,
                    DecorationType = magic.DecorationType
                };
                decoration.RenderTransform = new TranslateTransform() {
                    X = enemy.ComponentsOffset.X,
                    Y = enemy.ComponentsOffset.Y
                };
                enemy.RootCanvas.Children.Add(decoration);
            }
            //战后处理
            BattleHandle(magicer, enemy, injure);
        }

        /// <summary>
        /// 移除附加效果
        /// </summary>
        /// <param name="spirit">对象精灵</param>
        /// <param name="extraAttribute">附加效果代号</param>
        public static void RemoveAdditionalEffect(QXSprite sprite, int additionalEffectCode) {
            sprite.AdditionalEffectTime[additionalEffectCode] = 0;
            switch (additionalEffectCode) {
                case 0:
                    //麻痹
                    sprite.Buff[5] = 0; sprite.Buff[6] = 0; sprite.Buff[7] = 0;
                    sprite.Action = Actions.Stop;
                    break;
                case 1:
                    //混乱
                    break;
                case 2:
                    //冰冻
                    RemoveObject(sprite.RootCanvas.FindName(string.Format("Decoration{0}", additionalEffectCode)) as QXDecoration, true);
                    sprite.Action = Actions.Stop;
                    break;
                case 3:
                    //中毒
                    break;
                case 4:
                    //燃烧
                    sprite.Buff[9] = 0; sprite.Buff[10] = 0; sprite.Buff[12] = 0;
                    break;
                case 5:
                    //虚弱
                    sprite.Buff[1] = 0; sprite.Buff[2] = 0; sprite.Buff[13] = 0; sprite.Buff[14] = 0; sprite.Buff[15] = 0;
                    break;
            }
            //如果还有别的效果在,则附加上它的颜色
            for (int i = 0; i < sprite.AdditionalEffectTime.Count(); i++) {
                if (sprite.AdditionalEffectTime[i] > 0) {
                    sprite.MaskColor = new SolidColorBrush(AdditionalEffectColor[i]);
                    break;
                }
            }
        }

        /// <summary>
        /// 战后处理
        /// </summary>
        /// <param name="attacker">攻击者</param>
        /// <param name="enemy">敌人</param>
        /// <param name="injure">伤害</param>
        public static void BattleHandle(QXSprite attacker, QXSprite enemy, double injure) {
            if (enemy.VLife <= injure) {
                enemy.VLife = 0;
                enemy.LockObject = null;
                //移除所有附加效果
                for (int i = 0; i < enemy.AdditionalEffectTime.Count(); i++) {
                    enemy.AdditionalEffectTime[i] = 0;
                }
                enemy.Action = Actions.Death;
                RemoveStoryboard(enemy.Name);
                if (attacker.Name == "Leader") {
                    EarnExperience(attacker, enemy.VExperience);
                    ShowText(attacker, FontWeights.Bold, FontStyles.Normal, string.Format("经验 + {0}", enemy.VExperience), 26, Color.FromArgb(255, 212, 69, 224));
                }
            } else {
                if (enemy.LockObject == null && enemy.Name != "Leader") {
                    enemy.PKMode = PKModes.Whole;
                    enemy.LockObject = attacker.Name;
                }
                enemy.VLife -= injure;
            }
        }

        public static int[] LevelUpExperienceList;
        /// <summary>
        /// 增加经验值
        /// </summary>
        /// <param name="sprite">对象精灵</param>
        /// <param name="value">增加值</param>
        public static void EarnExperience(QXSprite sprite, int value) {
            //如果OL版还需要加入判断杀它的人是否为玩家
            if (sprite.VExperience + value >= LevelUpExperienceList[sprite.VLevel + 1]) {
                //等级+1
                sprite.VLevel += 1;
                //多出来的经验
                value = sprite.VExperience + value - LevelUpExperienceList[sprite.VLevel];
                //当前经验归0
                sprite.VExperience = 0;
                //添加装饰效果
                sprite.ParentCanvas.Children.Add(new QXDecoration() {
                    Code = 5,
                    EndFrame = 8,
                    BodyWidth = 200,
                    BodyHeight = 160,
                    CenterX = 100,
                    CenterY = 100,
                    Coordinate = sprite.Coordinate,
                    DecorationType = DecorationTypes.AutoRemove
                });
                ShowText(sprite, FontWeights.Bold, FontStyles.Normal, string.Format("升至{0}级", sprite.VLevel), 30, Colors.Yellow);
                //再重复检验一次，防止经验超过几级
                EarnExperience(sprite, value);
            } else {
                sprite.VExperience += value;
            }
        }

        /// <summary>
        /// 移除对象
        /// </summary>
        /// <param name="clearFromParent">是否将之从父对象中清除</param>
        /// <param name="obj">对象</param>
        public static void RemoveObject(IObject obj, bool clearFromParent) {
            if (obj is QXSprite) {
                QXSprite sprite = obj as QXSprite;
                RemoveStoryboard(sprite.Name);
                for (int i = 0; i < sprite.RootCanvas.Children.Count; i++) {
                    if (sprite.RootCanvas.Children[i] is QXDecoration) {
                        RemoveObject(sprite.RootCanvas.Children[i] as QXDecoration, true);
                    }
                }
                //从mini地图中移除掉该对应的对象点
                QXMiniMap miniMap = (sprite.ParentCanvas.Parent as Canvas).FindName("MiniMap") as QXMiniMap;
                UIElement uie = miniMap.MiniMap.FindName(string.Format("Obj{0}", sprite.Name)) as UIElement;
                if (uie != null) {
                    miniMap.MiniMap.Children.Remove(uie);
                    uie = null;
                }
            }
            if (clearFromParent) { obj.ParentCanvas.Children.Remove(obj as UIElement); }
            obj.Timer.Stop();
            obj.Timer = null;
            obj.RootCanvas.Children.Clear();
            obj = null;
        }
        public static QXMagic GetMagicByCode(string code)
        {
            XElement magicData, magicValue;
            int consumption;
            Queue<QXMagic> queue = Globle.MagicList[code];
            if (queue.Count == 0)
            {
                Super.LoadXElement(string.Format("Magic{0}", code), Super.GetXElement(Super.Settings["Arguments"], "Magic", "Code", code));
                magicData = Super.Settings[string.Format("Magic{0}", code)];
                magicValue = Super.GetXElement(magicData, "Level", "Value", "1");
                consumption = (int)magicValue.Attribute("Consumption");
                QXMagic magic = new QXMagic()
                  {

                      EndFrame = (int)magicData.Attribute("EndFrame"),
                      EffectiveFrame = (int)magicData.Attribute("EffectiveFrame"),
                      Code = Int32.Parse(code),
                      Mode = (int)magicData.Attribute("Mode"),
                      BodyWidth = (int)magicData.Attribute("BodyWidth"),
                      BodyHeight = (int)magicData.Attribute("BodyHeight"),
                      CenterX = (double)magicData.Attribute("CenterX"),
                      CenterY = (double)magicData.Attribute("CenterY"),
                      Radius = (int)magicData.Attribute("Radius"),
                      ATK = (int)magicValue.Attribute("ATK"),
                      Consumption = consumption,
                      AdditionalEffectCode = (int)magicData.Attribute("AdditionalEffectCode"),
                      AdditionalEffect = (int)magicValue.Attribute("AdditionalEffect"),
                      AdditionalEffectTime = (int)magicValue.Attribute("AdditionalEffectTime"),
                      DecorationCode = (int)magicData.Attribute("DecorationCode"),
                      DecorationWidth = (double)magicData.Attribute("DecorationWidth"),
                      DecorationHeight = (double)magicData.Attribute("DecorationHeight"),
                      DecorationEndFrame = (int)magicData.Attribute("DecorationEndFrame"),
                      DecorationType = (DecorationTypes)((int)magicData.Attribute("DecorationType")),
                  };
                return magic;
            }
            else {
                QXMagic tmp=queue.Dequeue();
                tmp.InitTimer();
                return tmp;
            }
        }
        public static QXDecoration GetCursorByCode(int code)
        {
            if (Globle.CursorList[code.ToString()].Count > 0)
            {
                QXDecoration tmp = Globle.CursorList[code.ToString()].Dequeue();
                tmp.Timer.Start();
                return tmp;
            }
            else {
                QXDecoration hitCursor = new QXDecoration()
                {
                    Code = code,
                    EndFrame = 9,
                    Width = 64,
                    Height = 64,
                    CenterX = 32,
                    CenterY = 32,
                    DecorationType = DecorationTypes.AutoRemove,
                    Name = "Cursor"
                };
                return hitCursor;
            }

        }
        public static void RecyclingMagic(QXMagic magic)
        {
            magic.InitTimer();
            magic.FrameCounter = magic.StartFrame;
            Globle.MagicList[magic.Code.ToString()].Enqueue(magic);
        }
        public static void RecyclingCursor(QXDecoration cursor)
        {
            cursor.InitTimer();
            cursor.FrameCounter = cursor.StartFrame;
            Globle.CursorList[cursor.Code.ToString()].Enqueue(cursor);
        }

    }
}
